import re
from datetime import datetime
from typing import Any, Dict, List, Optional, Union

class Validator:
    """
    数据验证基类
    """
    def __init__(self, error_message: str = "数据验证失败"):
        self.error_message = error_message
    
    def validate(self, value: Any) -> bool:
        """
        验证数据是否有效
        """
        raise NotImplementedError
    
    def get_error(self) -> str:
        """
        获取验证错误信息
        """
        return self.error_message

class RequiredValidator(Validator):
    """
    必填字段验证器
    """
    def __init__(self, error_message: str = "此字段为必填项"):
        super().__init__(error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return False
        if isinstance(value, str) and not value.strip():
            return False
        if isinstance(value, (list, tuple, dict)) and not value:
            return False
        return True

class MinLengthValidator(Validator):
    """
    最小长度验证器
    """
    def __init__(self, min_length: int, error_message: str = None):
        self.min_length = min_length
        if error_message is None:
            error_message = f"长度不能小于{min_length}个字符"
        super().__init__(error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return True  # 如果值为None，不进行长度验证（应由RequiredValidator处理）
        return len(str(value)) >= self.min_length

class MaxLengthValidator(Validator):
    """
    最大长度验证器
    """
    def __init__(self, max_length: int, error_message: str = None):
        self.max_length = max_length
        if error_message is None:
            error_message = f"长度不能超过{max_length}个字符"
        super().__init__(error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return True  # 如果值为None，不进行长度验证（应由RequiredValidator处理）
        return len(str(value)) <= self.max_length

class NumericValidator(Validator):
    """
    数字验证器
    """
    def __init__(self, error_message: str = "请输入有效的数字"):
        super().__init__(error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return True
        try:
            float(value)
            return True
        except (ValueError, TypeError):
            return False

class IntegerValidator(Validator):
    """
    整数验证器
    """
    def __init__(self, error_message: str = "请输入有效的整数"):
        super().__init__(error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return True
        try:
            int(value)
            return True
        except (ValueError, TypeError):
            return False

class PositiveValidator(Validator):
    """
    正数验证器
    """
    def __init__(self, error_message: str = "请输入正数"):
        super().__init__(error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return True
        try:
            num = float(value)
            return num > 0
        except (ValueError, TypeError):
            return False

class RegexValidator(Validator):
    """
    正则表达式验证器
    """
    def __init__(self, regex: str, error_message: str = "格式不正确"):
        self.regex = regex
        super().__init__(error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return True
        return bool(re.match(self.regex, str(value)))

class FormValidator:
    """
    表单验证器
    """
    def __init__(self):
        self.rules = {}
        self.errors = {}
    
    def add_field(self, field_name: str, *validators: Validator):
        """
        添加字段验证规则
        """
        self.rules[field_name] = validators
        return self
    
    def validate(self, data: Dict[str, Any]) -> bool:
        """f
        验证表单数据
        """
        self.errors = {}
        
        for field_name, validators in self.rules.items():
            value = data.get(field_name)
            for validator in validators:
                if not validator.validate(value):
                    if field_name not in self.errors:
                        self.errors[field_name] = []
                    self.errors[field_name].append(validator.get_error())
        
        return len(self.errors) == 0
    
    def get_errors(self) -> Dict[str, List[str]]:
        """
        获取验证错误信息
        """
        return self.errors
    
    def get_first_error(self) -> Optional[str]:
        """
        获取第一个错误信息
        """
        for field_errors in self.errors.values():
            if field_errors:
                return field_errors[0]
        return None